package welsir.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import welsir.entity.dos.Article;
import welsir.entity.dos.ArticleClass;
import welsir.entity.dos.User;
import welsir.entity.vo.ArticlePageVO;
import welsir.entity.vo.ArticleVO;
import welsir.entity.vo.ResultMessage;
import welsir.mapper.ArticleClassMapper;
import welsir.mapper.ArticleMapper;
import welsir.mapper.UserMapper;
import welsir.service.IArticleCommentService;
import welsir.service.IArticleService;
import welsir.service.IUserService;
import welsir.util.ResultUtil;

import javax.annotation.Resource;
import java.util.*;

/**
 * @author Genius
 * @date 2023/03/08 00:51
 **/
@Api(value = "web端文章后台管理")
@RequestMapping("/webArticle")
@RestController
public class WebArticleController {
    @Autowired
    private IArticleService articleService;
    @Resource
    private ArticleMapper articleMapper;
    @Resource
    private UserMapper userMapper;

    @Autowired
    private IUserService userService;

    @Autowired
    private IArticleCommentService articleCommentService;
    @Resource
    private ArticleClassMapper articleClassMapper;

    /**
     * 根据id获取文章
     * @param articleId
     * @return
     */
    @ApiOperation(value = "根据uid获取文章")
    @GetMapping("/getArticleById/{id}")
    public ResultMessage<Article> getArticleById(
            @PathVariable("id") Integer articleId
    ) {
        Article article = articleMapper.selectOne(new QueryWrapper<Article>().eq("article_id", articleId));
        String sortClass = article.getSortClass();
        QueryWrapper<ArticleClass> wrapper = new QueryWrapper<>();
        wrapper.eq("id",sortClass);
        ArticleClass articleClass = articleClassMapper.selectOne(wrapper);
        String name = articleClass.getName();
        Article articleBuffer = new Article();
        BeanUtils.copyProperties(article,articleBuffer);
        articleBuffer.setSortClass(name);
        return ResultUtil.data(articleBuffer);
    }

    /**
     * 获取全部文章列表
     * @param page
     * @param limit
     * @param click
     * @return
     */
    @ApiOperation(value = "分页获取所有文章列表")
    @GetMapping("/getAllArticle/{page}/{limit}/{click}")
    public ResultMessage<ArticlePageVO> getAllArticle(
            @PathVariable("page") Integer page,
            @PathVariable("limit") Integer limit,
            @PathVariable("click") Integer click
    ) {
        return ResultUtil.data(articleService.VoList(page,limit,click));
    }

    /**
     * 获取最新文章列表
     * @param articleNum
     * @param check
     * @return
     */
    @ApiOperation(value = "获取最新文章列表")
    @GetMapping("/getNewArticle/{articleNum}/{check}")
    public ResultMessage<List<ArticleVO>> getNewAllArticle(
            @PathVariable("articleNum") Integer articleNum,
            @PathVariable("check") String check
    ) {
        List<ArticleVO> result = new ArrayList<>();

        ArticleVO articleVO = null;

        QueryWrapper<Article> wrapper = new QueryWrapper<Article>();
        //wrapper限制查询数量
        wrapper.last("limit " + articleNum);
        if(check.equals("new")) {
            wrapper.orderByDesc("id");
        }
        if(check.equals("love")) {
            wrapper.orderByDesc("love_num");
        }
        if(check.equals("recommend")) {
            wrapper.orderByDesc("owner_tag");
        }
        if(check.equals("download")) {
            wrapper.orderByDesc("hits");
        }
        if(check.equals("discuss")) {
            wrapper.orderByDesc("post_num");
        }
        List<Article> articles = articleMapper.selectList(wrapper);
        for (Article article : articles) {
            articleVO = new ArticleVO();
            QueryWrapper<ArticleClass> wrapper1 = new QueryWrapper<>();
            wrapper1.eq("id",article.getSortClass());
            ArticleClass articleClass = articleClassMapper.selectOne(wrapper1);
            String name = articleClass.getName();
            BeanUtils.copyProperties(article,articleVO);
            articleVO.setClassName(name);
            result.add(articleVO);
        }
        return ResultUtil.data(result);
    }

    /**
     * 获取全部文章数量
     * @return
     */
    @ApiOperation(value = "获取所有文章数量")
    @GetMapping("/getAllArticleNumber")
    public ResultMessage<Integer> getAllArticleNumber() {
        QueryWrapper<Article> wrapper = new QueryWrapper<>();
        wrapper.select().eq("status","published");
        return ResultUtil.data(articleMapper.selectCount(wrapper));
    }

   /**
    * 获取全部文章数量
    * @return
    */
   // TODO: 2023/3/8
    @GetMapping("/articles/{id}/view")
    public ResultMessage<Boolean> articlesViewBrowse(
            @PathVariable("id") Integer id
    ) {
        return ResultUtil.data(articleService.articlesBrowse(id));
    }

    /**
     * 统计文章喜欢量+1
     * @param id
     * @return
     */
    @ApiOperation(value = "统计文章喜欢量+1")
    @ApiImplicitParam(name = "id",value = "文章id",required = true)
    @GetMapping("/articles/{id}/love")
    public ResultMessage<Boolean> articlesLoveBrowse(
            @PathVariable("id") Integer id
    ) {
        return ResultUtil.data(articleService.articlesLoveBrowse(id));
    }

    /**
     * 文章查询全部
     * @param content
     * @return
     */
    @ApiOperation(value = "文章查询(全部)")
    @ApiImplicitParam(name = "content",value = "模糊查询标题",required = true)
    @GetMapping("/findArticles/{content}")
    public ResultMessage<List<Article>> findArticles(
            @PathVariable("content") String content
    ) {
        QueryWrapper<Article> wrapper = new QueryWrapper<>();
        wrapper.like("title",content);
        return ResultUtil.data(articleMapper.selectList(wrapper));
    }

    /**
     * 文章查询(预览)
     * @param content
     * @param num
     * @return
     */
    @ApiOperation(value = "文章查询(预览)")
    @ApiImplicitParam(name = "content",value = "模糊查询标题",required = true)
    @GetMapping("/findArticlesByNum/{content}/{num}")
    public ResultMessage<List<Article>> findArticlesByNum(
            @PathVariable("content") String content,
            @PathVariable("num") String num
    ) {
        QueryWrapper<Article> wrapper = new QueryWrapper<>();
        wrapper.like("title",content)
                .last("limit "+num);
        return ResultUtil.data(articleMapper.selectList(wrapper));
    }

    /**
     * 文章查询(分页)
     * @param content
     * @param page
     * @param limit
     * @return
     */
    @ApiOperation(value = "查询文章(分页)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "content",value = "内容",required = true),
            @ApiImplicitParam(name = "page",value = "页数",required = true),
            @ApiImplicitParam(name = "limit",value = "总量",required = true)
    })
    @GetMapping("/findAllArticle/{content}/{page}/{limit}")
    public ResultMessage<ArticlePageVO> findAllArticle(
            @PathVariable("content") String content,
            @PathVariable("page") Integer page,
            @PathVariable("limit") Integer limit
    ) {
        return ResultUtil.data(articleService.FindVoList(page, limit , content));
    }

    /**
     * 根据作者name查询对应头像
     * @param name
     * @return
     */
    @ApiOperation(value = "根据作者name查询对应头像")
    @ApiImplicitParam(name = "name",value = "作者名称",required = true)
    @GetMapping("/findProfileByName/{name}")
    public ResultMessage<String> FindProfileByName(
            @PathVariable("name") String name
    ) {
        QueryWrapper<User> Wrapper = new QueryWrapper<>();
        Wrapper.eq("username",name);
        User user = this.userMapper.selectOne(Wrapper);
        return ResultUtil.data(user.getAvatar());
    }

    /**
     * 获取重要文章
     * @return
     */
    @ApiOperation(value = "获取重要文章")
    @GetMapping("/getArticleMatter")
    public ResultMessage<List<ArticleVO>> GetArticleMatter(
    ) {
        List<ArticleVO> result = new ArrayList<>();

        QueryWrapper<Article> Wrapper = new QueryWrapper<>();
        Wrapper.select().orderByAsc("add_time");
        Wrapper.orderByDesc("owner_tag");
        Wrapper.last("limit 0,4");
        List<Article> articles = this.articleMapper.selectList(Wrapper);
        for (Article article : articles) {
            //获取id
            String aid = article.getArticleId();
            //获取对应评论数量
            int acnum = articleCommentService.GetCommentNum(Integer.parseInt(aid));
            //根据作者名称查询对应的头像地址
            String author = article.getAuthor();
            User users = userService.queryUserByUserName(author);
            String profile = users.getAvatar();
            //获取对应分类
            String sortClass = article.getSortClass();
            ArticleClass articleClass = articleClassMapper.selectById(sortClass);
            String classname = articleClass.getName();

            ArticleVO articleVOs = new ArticleVO();
            articleVOs.setAvatar(profile);
            articleVOs.setCommentNum(acnum);
            articleVOs.setClassName(classname);

            BeanUtils.copyProperties(article,articleVOs);
            result.add(articleVOs);
        }
        return ResultUtil.data(result);
    }

    /**
     * 获取文章上一页(标题)
     * @param id
     * @return
     */
    @ApiOperation(value = "获取文章上一页(标题)")
    @GetMapping("/getPreArticle/{id}")
    public ResultMessage<Map<String, Object>> getPreArticle(
            @PathVariable("id") String id
    ){
        QueryWrapper<Article> wrapper = new QueryWrapper<>();
        wrapper.
                gt("article_id", id) // 大于
                .orderByAsc("article_id")
                .last("limit 1");
        Article article = articleMapper.selectOne(wrapper);
        if (article == null) {
            Map<String, Object> list = new HashMap<String, Object>();
            Date date = new Date();
            list.put("title", "当前已是最新文章");
            list.put("addTime", date);
            list.put("createTime", date);
            list.put("id", 1);
            return ResultUtil.data(list);
        }
        String title = article.getTitle();
        Date addTime = article.getAddTime();
        Date createTime = article.getCreateTime();
        String id1 = article.getArticleId();
        Map<String, Object> list = new HashMap<String, Object>();
        list.put("title", title);
        list.put("addTime", addTime);
        list.put("createTime", createTime);
        list.put("articleId", id1);
        return ResultUtil.data(list);
    }


    /**
     * 获取文章下一页(标题)
     * @param id
     * @return
     */
    @ApiOperation(value = "获取文章下一页(标题)")
    @GetMapping("/getLastArticle/{id}")
    public ResultMessage<Map<String, Object>> getLastArticle(
            @PathVariable("id") String id
    ){
        QueryWrapper<Article> wrapper = new QueryWrapper<>();
        wrapper.
                lt("article_id", id) // 小于
                .orderByDesc("article_id")
                .last("limit 1");
        Article article = articleMapper.selectOne(wrapper);
        if (article == null) {
            return null;
        }
        String title = article.getTitle();
        Date addTime = article.getAddTime();
        Date createTime = article.getCreateTime();
        String id1 = article.getArticleId();
        Map<String, Object> list = new HashMap<String, Object>();
        list.put("title", title);
        list.put("addTime", addTime);
        list.put("createTime", createTime);
        list.put("articleId", id1);
        return ResultUtil.data(list);
    }
}
